package com.csun.cmny.provider.controller.admin;

import com.csun.cmny.base.dto.CheckValidDto;
import com.csun.cmny.core.annotation.OperationLogDto;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.model.constant.UacApiConstant;
import com.csun.cmny.provider.model.domain.UacUser;
import com.csun.cmny.provider.model.domain.UacUserSecurityQuestion;
import com.csun.cmny.provider.model.dto.device.DeviceReqDto;
import com.csun.cmny.provider.model.dto.user.*;
import com.csun.cmny.provider.model.enums.UacUserStatusEnum;
import com.csun.cmny.provider.model.vo.OldmanBedRoomBuildingVo;
import com.csun.cmny.provider.model.vo.UserSecurityVo;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.google.common.base.Preconditions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * 不认证的URL请求.
 *
 * @author paascloud.net @gmail.com
 */
@RestController
@RequestMapping(value = "/auth")
@Api(value = "Web-AuthRestController", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class AuthRestController extends BaseController {

	@Resource
	private UacUserService uacUserService;
	@Resource
	private SmsService smsService;
	@Resource
	private EmailService emailService;
	@Resource
	private UacLogService uacLogService;
	@Resource
	private DmcRpcService dmcRpcService;
	@Resource
	private OmcRpcService omcRpcService;
	@Resource
	private CmnyMessageSource cmnyMessageSource;
	@Resource
	private RestTemplate myRestTemplate;

	@Resource
	private UacUserSecurityService uacUserSecurityService;

	@PostMapping(value = "/getDeviceById/{id}")
	public Wrapper getDeviceById(@PathVariable Long id) {

		DeviceReqDto deviceReqDto = dmcRpcService.getDeviceById(id);

		//return WrapMapper.ok(deviceReqDto);
//		return WrapMapper.ok(cmnyMessageSource.getMessage("operation.success", null),
//				deviceReqDto);
		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null), deviceReqDto);

	}

	@PostMapping(value = "/queryOldmanBedRoomBuildingByOldmanId/{id}")
	public Wrapper queryOldmanBedRoomBuildingByOldmanId(@PathVariable Integer id) {

		OldmanBedRoomBuildingVo oldmanBedRoomBuildingVo = omcRpcService
				.queryOldmanBedRoomBuildingByOldmanId(id);

		//return WrapMapper.ok(oldmanBedRoomBuildingVo);
		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null), oldmanBedRoomBuildingVo);
	}

	/**
	 * 校验手机号码.
	 *
	 * @param mobileNo the mobile no
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/checkPhoneActive/{mobileNo}")
	@ApiOperation(httpMethod = "POST", value = "校验手机号码")
	public Wrapper<Boolean> checkPhoneActive(@PathVariable String mobileNo) {
		UacUser uacUser = new UacUser();
		uacUser.setStatus(UacUserStatusEnum.ENABLE.getKey());
		uacUser.setMobileNo(mobileNo);
		int count = uacUserService.selectCount(uacUser);
		//return WrapMapper.ok(count > 0);
		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null), count > 0);
	}

	/**
	 * 校验邮箱.
	 *
	 * @param email the email
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/checkEmailActive/{email:.+}")
	@ApiOperation(httpMethod = "POST", value = "校验邮箱")
	public Wrapper<Boolean> checkEmailActive(@PathVariable("email") String email) {
		UacUser uacUser = new UacUser();
		uacUser.setStatus(UacUserStatusEnum.ENABLE.getKey());
		uacUser.setEmail(email);
		int count = uacUserService.selectCount(uacUser);
		//return WrapMapper.ok(count > 0);
		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null), count > 0);
	}

	/**
	 * 校验数据.
	 *
	 * @param checkValidDto the check valid dto
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/checkValid")
	@ApiOperation(httpMethod = "POST", value = "校验数据")
	public Wrapper checkValid(@RequestBody CheckValidDto checkValidDto) {
		String type = checkValidDto.getType();
		String validValue = checkValidDto.getValidValue();

		Preconditions.checkArgument(StringUtils.isNotEmpty(validValue), "参数错误");
		String message = null;
		boolean result = false;
		//开始校验
		if (UacApiConstant.Valid.LOGIN_NAME.equals(type)) {
			result = uacUserService.checkLoginName(validValue);
			if (!result) {
				message = "用户名已存在";
			}
		}
		if (UacApiConstant.Valid.EMAIL.equals(type)) {
			result = uacUserService.checkEmail(validValue);
			if (!result) {
				message = "邮箱已存在";
			}
		}

		if (UacApiConstant.Valid.MOBILE_NO.equals(type)) {
			result = uacUserService.checkMobileNo(validValue);
			if (!result) {
				message = "手机号码已存在";
			}
		}

		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, message, result);
	}


	/**
	 * 重置密码-邮箱-提交.
	 *
	 * @param email the email
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/submitResetPwdEmail")
	@ApiOperation(httpMethod = "POST", value = "重置密码-邮箱-提交")
	public Wrapper<String> submitResetPwdEmail(@RequestParam("email") String email) {
		logger.info("重置密码-邮箱-提交, email={}", email);
		emailService.submitResetPwdEmail(email);
		//return WrapMapper.ok();
		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null));
	}


	/**
	 * 重置密码-手机-提交.
	 *
	 * @param mobile   the mobile
	 * @param response the response
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/submitResetPwdPhone")
	@ApiOperation(httpMethod = "POST", value = "重置密码-手机-提交")
	public Wrapper<String> submitResetPwdPhone(@RequestParam("mobile") String mobile, HttpServletResponse response) {
		logger.info("重置密码-手机-提交, mobile={}", mobile);
		String token = smsService.submitResetPwdPhone(mobile, response);
		//return WrapMapper.ok(token);
		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null), token);
	}

	/**
	 * 重置密码-最终提交.
	 *
	 * @param resetLoginPwdDto the reset login pwd dto
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/resetLoginPwd")
	@ApiOperation(httpMethod = "POST", value = "重置密码-最终提交")
	public Wrapper<Boolean> checkResetSmsCode(@RequestBody ResetLoginPwdDto resetLoginPwdDto) {
		uacUserService.resetLoginPwd(resetLoginPwdDto);
		//return WrapMapper.ok();
		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null));
	}

	@PostMapping(value = "/phoneResetLoginPwd")
	@ApiOperation(httpMethod = "POST", value = "重置密码-手机-提交")
	public Wrapper<Boolean> phoneResetLoginPwd(PhoneResetLoginPwdDto phoneResetLoginPwdDto) {

		System.out.println("phoneResetLoginPwdDto ==> " + phoneResetLoginPwdDto);

		uacUserService.phoneResetLoginPwd(phoneResetLoginPwdDto);

		//return WrapMapper.ok();
		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null));
	}

	/**
	 * 注册用户.
	 *
	 * @param user the user
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/register")
	@ApiOperation(httpMethod = "POST", value = "注册用户")
	public Wrapper registerUser(UserRegisterDto user) {
		uacUserService.register(user);
		//return WrapMapper.ok();
		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null));
	}

	/**
	 * 家属版注册新用户
	 *
	 * @param registerDto the register dto
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/phoneRegister")
	public Wrapper phoneRegister(UserRegisterDto registerDto) {

		logger.info("注册参数：{}", registerDto);

		uacUserService.phoneRegister(registerDto);

		//return WrapMapper.ok();
		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null));
	}

	/**
	 * 激活用户.
	 *
	 * @param activeUserToken the active user token
	 *
	 * @return the wrapper
	 */
	@GetMapping(value = "/activeUser/{activeUserToken}")
	@ApiOperation(httpMethod = "POST", value = "激活用户")
	public Wrapper activeUser(@PathVariable String activeUserToken) {
		uacUserService.activeUser(activeUserToken);
		//return WrapMapper.ok("激活成功");
		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null), "激活成功");
	}

	/**
	 * 保存日志.
	 *
	 * @param operationLogDto the operation log dto
	 *
	 * @return the integer
	 */
	@PostMapping(value = "/saveLog")
	@ApiOperation(httpMethod = "POST", value = "保存日志")
	public Integer saveLog(@RequestBody OperationLogDto operationLogDto) {
		logger.info("saveLog - 保存操作日志. operationLogDto={}", operationLogDto);
		return uacLogService.saveOperationLog(operationLogDto);
	}

	@PostMapping(value = "/callback/qq")
	public void callbackQQ(HttpServletRequest request) {
		logger.info("callback - callback qq. request={}", request);
	}

	/**
	 * 查询安全问题列表.
	 *
	 * @param
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/querySecurityQuestionList")
	@ApiOperation(httpMethod = "POST",value = "查询安全问题列表")
	public Wrapper querySecurityQuestionList(){

		List<UacUserSecurityQuestion> questionList = uacUserSecurityService.querySecurityQuestionList();

		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null), questionList);
	}

	/**
	 * 查询用户安全问题列表.
	 *
	 * @param loginName 用户登录名
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/queryUserSecurityQuestionList/{loginName}")
	@ApiOperation(httpMethod = "POST",value = "查询安全问题列表")
	public Wrapper queryUserSecurityQuestionList(@PathVariable String loginName){

		UserSecurityVo userSecurityVo = uacUserSecurityService.queryUserSecurityQuestionList(loginName);

		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null), userSecurityVo);
	}

	/**
	 * 添加安全问题.
	 *
	 * @param
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/addSecurityQuestion")
	@ApiOperation(httpMethod = "POST",value = "添加安全问题")
	public Wrapper addSecurityQuestion(@RequestBody UserSecurityQuestionDto userSecurityQuestionDto){

//		userSecurityQuestionDto.setUserId(getLoginAuthDto().getUserId().intValue());
		int result=uacUserSecurityService.addSecurityQuestion(userSecurityQuestionDto);

		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null), result);
	}

	/**
	 * 校验安全问题.
	 *
	 * @param checkSecurityQuestionDto the check security question dto
	 *
	 * @return the wrapper
	 */
	@PostMapping(value = "/checkQuestionActive")
	@ApiOperation(httpMethod = "POST",value = "校验安全问题")
	public Wrapper<String> checkQuestionActive(@RequestBody CheckSecurityQuestionDto checkSecurityQuestionDto,HttpServletResponse response){

		String active = uacUserSecurityService.checkQuestionActive(checkSecurityQuestionDto,response);

		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null), active);
	}


	@PostMapping(value = "/testUpload")
	public Wrapper testUpload(String month) {

		String filePathPrefix = "G:\\report\\";
		String filePath = filePathPrefix + "csun-sleep-" + month + ".json";
		String zipFilePath = filePathPrefix + "MS005-" + month + ".zip";

		File zip = new File(zipFilePath);

		MultiValueMap mvm = new LinkedMultiValueMap();
		mvm.add("file", new FileSystemResource(zip));

		String url = "http://218.64.194.48:7780/products/mattress/MS005";

		HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
//		headers.add("Content-Type", "application/zip");

		HttpEntity httpEntity = new HttpEntity<>(mvm, headers); // 组装

		Object object = myRestTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);

		return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
				.getMessage("operation.success", null), object);
	}

}
